<template>
  <div class="app-container">
    <NavBarBread :bread="[$route.meta.parentName, $route.meta.menuName]">
      <el-button type="text" style="margin-right:20px; color: #05A7aB;" @click="handelImport">导入</el-button>
      <el-tooltip class="item" effect="dark" content="导出" placement="top-end">
        <i class="el-icon-sold-out" style="font-size: 20px; color: #05A7aB;" @click="handelExport" />
      </el-tooltip>
    </NavBarBread>
    <div class="serach-container">
      <div class="search-inputs">
        <el-form :inline="true" :model="simpleForm" class="demo-form-inline searchCondition" label-position="right" label-width="100px">
          <el-form-item label="店代码">
            <el-input v-model="simpleForm.dealerCode" placeholder="请输入店代码" />
          </el-form-item>
          <el-form-item label="店简称">
            <el-input v-model="simpleForm.dealerName" placeholder="请输入店简称" />
          </el-form-item>
          <el-form-item label="店类型">
            <el-select v-model="simpleForm.dealerType" clearable placeholder="请选择店类型">
              <el-option label="出行中心店" :value="0" />
              <el-option label="非出行中心店" :value="1" />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="queryTableList">查询</el-button>
          <el-button @click="handelRest">重置</el-button>
        </el-form>
        <el-collapse-transition>
          <div v-if="isMore" class="more-container">
            <el-form :inline="true" :model="complexForm" class="demo-form-inline searchCondition" label-position="right" label-width="100px">
              <el-form-item label="大区">
                <el-select v-model="complexForm.bigAreaCode" clearable placeholder="请选择大区">
                  <el-option v-for="(item, index) in regions" :key="index + '_' + item.bigAreaCode" :label="item.bigAreaName" :value="item.bigAreaCode" />
                </el-select>
              </el-form-item>
              <el-form-item label="姓名">
                <el-input v-model="complexForm.name" placeholder="请输入姓名" />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="complexForm.status" clearable placeholder="请选择报警是否下发">
                  <el-option label="禁用" :value="0" />
                  <el-option label="启用" :value="1" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-transition>
      </div>
      <div class="search-toggle">
        <el-button
          type="text"
          @click="handelToggle"
        >
          {{ isMore ? '普通搜索' : '高级搜索' }}
        </el-button>
      </div>
    </div>
    <div class="section-container">
      <el-table v-loading="listLoading" size="mini" :data="tables.data" border fit highlight-current-row style="width: 100%" height="600">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column v-for="item in tables.columns" :key="item.key" :label="item.lable" :width="item.width" :align="item.align" :show-overflow-tooltip="true">
          <template slot-scope="{row}">
            <span v-if="item.key === 'dealerType'">{{ !!row.dealerType ? '非出行中心店' : '出行中心店' }}</span>
            <span v-else>{{ row[item.key] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" :show-overflow-tooltip="true">
          <template slot-scope="{row}">
            <span>{{ row.status ? '启用' : '禁用' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="240" fixed="right">
          <template slot-scope="{row}">
            <div class="actions-columns">
              <el-button type="text" size="small" @click="handelCheck(row)">查看</el-button>
              <el-button type="text" size="small" @click="handelEdit(row)"> 修改</el-button>
              <el-button type="text" size="small" @click="handelSwitchStatus(row)">{{ row.status ? '禁用' : '启用' }}</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="total" :page.sync="pages.page" :limit.sync="pages.limit" @pagination="changePages" />
    </div>

    <!-- 详情弹窗 -->
    <el-dialog title="查看" :visible.sync="checkVisible" width="40%">
      <div class="detailContainer">
        <div v-for="item in tables.columns" :key="item.key" class="detailItem">
          <div v-if="item.key === 'dealerType'">
            <span class="detailTitle">{{ item.lable }}：</span>
            <span class="detailContent">{{ currents[item.key] ? '非出行中心店' : '出行中心店' }}</span>
          </div>
          <div v-else>
            <span class="detailTitle">{{ item.lable }}：</span>
            <span class="detailContent">{{ currents[item.key] }}</span>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="checkVisible = false">确 认</el-button>
        <el-button @click="checkVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改弹窗 -->
    <el-dialog title="修改" :visible.sync="editVisible" width="750px">
      <el-form ref="ruleForm" :inline="true" :model="ruleForm" label-width="120px" class="demo-ruleForm">
        <div>
          <el-form-item label="店简称">
            <el-input v-model="ruleForm.dealerName" disabled />
          </el-form-item>
          <el-form-item label="店编码">
            <el-input v-model="ruleForm.dealerCode" disabled />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="店类型">
            <el-select v-model="ruleForm.dealerType" disabled style="width: 100%;" placeholder="请选择店类型">
              <el-option label="出行中心店" :value="0" />
              <el-option label="非出行中心店" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="大区">
            <el-select v-model="ruleForm.bigAreaCode" disabled placeholder="请选择大区">
              <el-option v-for="(item, index) in regions" :key="index + '_' + item.bigAreaCode" :label="item.bigAreaName" :value="item.bigAreaCode" />
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="大区总监"
            prop="bigAreaCdo"
            :rules="[
              { required: true, message: '请输入姓名', trigger: 'blur' },
            ]"
          >
            <el-input v-model="ruleForm.bigAreaCdo" />
          </el-form-item>
          <el-form-item
            label="大区总监邮箱"
            prop="bigAreaCdoEmail"
            :rules="[
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
            ]"
          >
            <el-input v-model="ruleForm.bigAreaCdoEmail" />
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="大区经理"
            prop="bigAreaGm"
            :rules="[
              { required: true, message: '请输入姓名', trigger: 'blur' },
            ]"
          >
            <el-input v-model="ruleForm.bigAreaGm" />
          </el-form-item>
          <el-form-item
            label="大区经理邮箱"
            prop="bigAreaGmEmail"
            :rules="[
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
            ]"
          >
            <el-input v-model="ruleForm.bigAreaGmEmail" />
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="大区督导"
            prop="bigAreaSpv"
            :rules="[
              { required: true, message: '请输入姓名', trigger: 'blur' },
            ]"
          >
            <el-input v-model="ruleForm.bigAreaSpv" />
          </el-form-item>
          <el-form-item
            label="大区督导邮箱"
            prop="bigAreaSpvEmail"
            :rules="[
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
            ]"
          >
            <el-input v-model="ruleForm.bigAreaSpvEmail" />
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="巡回员"
            prop="tourAttendant"
            :rules="[
              { required: true, message: '请输入姓名', trigger: 'blur' },
            ]"
          >
            <el-input v-model="ruleForm.tourAttendant" />
          </el-form-item>
          <el-form-item
            label="巡回员邮箱"
            prop="tourAttendantEmail"
            :rules="[
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
            ]"
          >
            <el-input v-model="ruleForm.tourAttendantEmail" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" :loading="uploadLoading" @click="comfirmUpdate('ruleForm')">确 认</el-button>
        <el-button @click="editVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog :title="!!!steps ? '导入' : '导入结果'" :visible.sync="detailVisible" width="60%">
      <div v-show="!!!steps" class="stepOne">
        <div class="title">1、数据整理</div>
        <div class="section">
          <div class="import-tips">请先导出列表数据后根据实际情况修改；数据字段不符合规则，整条数据不予以导入</div>
          <div class="actions">
            <div style="margin-top: 10px;">
              <!-- <i class="el-icon-download" style="color: #2aaca8"></i> -->
              <el-button :loading="uploadLoading" type="text" icon="el-icon-download" plain @click="handleExportAll">导出全部数据</el-button>
              <!-- <a id="template" type="info" href="/static/template/报警邮件抄送管理导入模版.xlsx" download="报警邮件抄送管理导入模版" target="_blank" style="color: #2aaca8">下载导入模版</a> -->
            </div>
            <!-- <el-button type="text" icon="el-icon-download">下载导入模版</el-button> -->
          </div>
        </div>
        <div class="title">2、上传数据文件</div>
        <div class="section">
          <div class="import-tips">支持的文件类型为xls、xlsx；文件大小不超过10M</div>
          <div class="actions">
            <input v-show="false" id="uploadFile" size="small" accept=".xlsx, .xls" type="file" @change="getFile($event)">
            <el-button :loading="uploadLoading" type="primary" icon="el-icon-upload2" plain @click="handleUpload">上传文件</el-button>
          </div>
          <div v-if="file">{{ file.name }}</div>
        </div>
      </div>
      <div v-show="!!steps" class="stepTwo">
        <div class="import-tips success"><span>{{ uploadSuccess.length }}</span>条数据将会被导入</div>
        <el-table size="mini" :data="uploadSuccess" border fit highlight-current-row style="width: 100%" height="300">
          <el-table-column type="index" label="序号" width="50" align="center" />
          <el-table-column v-for="item in tables.columns" :key="item.key" :label="item.lable" :width="item.width" :align="item.align" :show-overflow-tooltip="true">
            <template slot-scope="{row}">
              <span>{{ row[item.key] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="校验结果" align="center" width="100" :show-overflow-tooltip="true">
            <template slot-scope="{row}">
              <span>{{ row.result }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="import-tips fail"><span>{{ uploadFaile.length }}</span>条数据将不会被导入</div>
        <el-table size="mini" :data="uploadFaile" border fit highlight-current-row style="width: 100%;" height="300">
          <el-table-column type="index" label="序号" width="50" align="center" />
          <el-table-column v-for="item in tables.columns" :key="item.key" :label="item.lable" :align="item.align" :show-overflow-tooltip="true">
            <template slot-scope="{row}">
              <span v-if="row[item.key]" :class="[row.errorColumns.includes(item.key) ? 'isActive' : '']">{{ row[item.key] }}</span>
              <span v-else :class="[row.errorColumns.includes(item.key) ? 'isActive' : '']">数据缺失</span>
            </template>
          </el-table-column>
          <el-table-column label="校验结果" align="center" width="100" :show-overflow-tooltip="true">
            <template slot-scope="{row}">
              <span>{{ row.result }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button v-show="!!steps" type="primary" :loading="uploadLoading" @click="handleConfirmUpload">确认导入</el-button>
        <el-button v-show="!!steps" type="primary" @click="steps = 0">上一步</el-button>
        <el-button v-show="!!!steps" type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="detailVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { queryDealerEmail, exportDealerEmail, uploadDealerEmail, updateDealerEmail, updateDealerEmailStatus, insertDealerEmail } from '@/api/crossRegionalMonitoring'
import Pagination from '@/components/Pagination'
import NavBarBread from '@/components/NavBarBread'
import { downloadByUrl } from '@/utils/download'
import { exportExcelByBlob, getStorageByKey } from '@/utils/public'
export default {
  name: 'RealTimeAlarm',
  components: { Pagination, NavBarBread },
  data() {
    return {
      tables: {
        columns: [
          { lable: '店简称', key: 'dealerName', width: '100px', align: 'center' },
          { lable: '店代码', key: 'dealerCode', width: '100px', align: 'center' },
          { lable: '店类型', key: 'dealerType', width: '100px', align: 'center' },
          { lable: '大区', key: 'bigAreaName', width: '100px', align: 'center' },
          { lable: '大区总监', key: 'bigAreaCdo', width: '100px', align: 'center' },
          { lable: '大区总监邮箱', key: 'bigAreaCdoEmail', width: '160px', align: 'center' },
          { lable: '大区经理', key: 'bigAreaGm', width: '100px', align: 'center' },
          { lable: '大区经理邮箱', key: 'bigAreaGmEmail', width: '160px', align: 'center' },
          { lable: '大区督导', key: 'bigAreaSpv', width: '100px', align: 'center' },
          { lable: '大区督导邮箱', key: 'bigAreaSpvEmail', width: '160px', align: 'center' },
          { lable: '巡回员', key: 'tourAttendant', width: '100px', align: 'center' },
          { lable: '巡回员邮箱', key: 'tourAttendantEmail', width: '160px', align: 'center' }
        ],
        data: []
      },
      pages: {
        pageNum: 1,
        pageSize: 20
      },
      total: 0,
      listLoading: true,
      detailVisible: false,
      checkVisible: false,
      simpleForm: {},
      complexForm: {},
      isMore: false,
      multipleSelection: [],
      // 大区数据
      regions: getStorageByKey('regionsMap'),
      steps: 0,
      file: null,
      uploadLoading: false,
      uploadSuccess: [],
      uploadFaile: [],
      isUpload: false,
      currents: {},
      editVisible: false,
      ruleForm: {}
    }
  },
  created() {
    this.queryTableList()
  },
  methods: {
    handleExportAll() {
      downloadByUrl(process.env.SPANNED_MONITOR_SERVICE + 'v1/private/img-download/dealer-email-config-export')
      // exportDealerEmail().then(res => {
      //   const { data } = res
      //   const fileName = `${this.$route.meta.menuName}.xlsx`
      //   exportExcelByBlob(data, fileName)
      // })
    },
    changePages(params) {
      this.pages = { ...params }
      this.queryTableList()
    },
    async queryTableList() {
      this.listLoading = true
      const { data } = await queryDealerEmail(this.formatParams())
      this.tables.data = data.list
      this.total = data.total
      this.listLoading = false
    },
    handleConfirm() {
      if (!this.isUpload) {
        return this.$message({
          type: 'error',
          message: '请先上传文件或等待文件上传完毕'
        })
      }
      this.steps = 1
    },
    handleConfirmUpload() {
      this.uploadLoading = true
      insertDealerEmail(this.uploadSuccess).then(res => {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.detailVisible = false
        this.queryTableList()
      }).finally(()=> {
        this.uploadLoading = false
      })
    },
    comfirmUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.uploadLoading = true
          updateDealerEmail(this.ruleForm).then(res => {
            this.editVisible = false
            this.queryTableList()
          }).finally(() => {
            this.uploadLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    formatParams() {
      const params = { ...this.simpleForm, ...this.complexForm, ...this.pages }
      return params
    },
    // 清空查询条件
    handelRest() {
      for (const key in this.simpleForm) {
        this.simpleForm[key] = ''
      }
      this.clearComplexSearchCondetions()
    },
    // 清空复杂查询条件
    clearComplexSearchCondetions() {
      for (const key in this.complexForm) {
        this.complexForm[key] = ''
      }
    },
    handelToggle() {
      this.isMore = !this.isMore
      !this.isMore && this.clearComplexSearchCondetions()
    },
    // 启用/禁用
    handelSwitchStatus(row) {
      const { id, status } = row
      const params = { id, status: status ? 0 : 1 }
      if (status) {
        this.$confirm('此操作将禁用该店报警邮件发送，您确认要继续吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateDealerEmailStatus(params).then((res) => {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
            this.queryTableList()
          })
        })
      } else {
        updateDealerEmailStatus(params).then((res) => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          this.queryTableList()
        })
      }
    },
    handelCheck(row) {
      this.currents = row
      this.checkVisible = true
    },
    handelEdit(row) {
      this.ruleForm = { ...row }
      this.editVisible = true
    },
    getFile(event) {
      this.file = event.target.files[0]
      this.uploadLoading = true
      const formData = new FormData()
      formData.append('file', this.file)
      uploadDealerEmail(formData).then(res => {
        const { data } = res
        const { successList, errorList } = data
        this.uploadSuccess = successList
        this.uploadFaile = errorList
        this.isUpload = true
        this.steps = 1
      }).finally(() => {
        this.uploadLoading = false
        event.target.value = ''
      })
    },
    handleUpload() {
      document.getElementById('uploadFile').click()
    },
    handelImport() {
      this.detailVisible = true
      this.isUpload = false
      this.steps = 0
      this.file = null
    },
    handelExport() {
      const params = this.formatParams()
      this.$delete(params, 'pageNum')
      this.$delete(params, 'pageSize')
      downloadByUrl(process.env.SPANNED_MONITOR_SERVICE + 'v1/private/img-download/dealer-email-config-export', params)
      // exportDealerEmail(params).then(res => {
      //   const { data } = res
      //   const fileName = `${this.$route.meta.menuName}.xlsx`
      //   exportExcelByBlob(data, fileName)
      // })
    }
  }
}
</script>
<style scoped>
  ::v-deep .el-dialog__body{
    padding: 0px 20px;
  }
  ::v-deep(.el-form-item .el-form-item__content){
    width: 200px;
  }
  .el-input{
    width: 202px;
  }
  ::v-deep .actions-columns .el-button{
    padding: 0px;
  }
</style>
<style lang="scss" scoped>
  $red:#C03639;
  $green: #30B08F;
  .isActive{
    color: $red;
  }
  .serach-container{
    width: 100%;
    display: flex;
    justify-content: space-between;
    // .search-inputs{
    //   width: 90%;
    // }
  }
  .tool-container{
    width: 100%;
    display: flex;
    justify-content: space-between;
    line-height: 40px;
    .toggle-warning{
      font-family: 'PingFangSC-Semibold', 'PingFang SC Semibold', 'PingFang SC', sans-serif;
      font-weight: 650;
      font-style: normal;
      font-size: 16px;
    }
  }
  .stepOne{
    .title{
      color: #333;
      line-height: 50px;
      font-weight: 650;
    }
    .section{
      width: 100%;
      box-sizing: border-box;
      padding-left: 20px;
      .actions{
        margin: 10px 0px 20px 0px;
      }
    }
  }
  .stepTwo{
    .import-tips{
      line-height: 30px;
      span{
        margin-right: 5px;
      }
    }
    .success{
      span{
        color: $green;
      }
    }
    .fail{
      margin-top: 5px;
      span{
        color: $red;
      }
    }
  }
  .detailContainer {
    display: flex;
    flex-wrap: wrap;
    padding: 0 15px;
    width: 100%;
    .detailItem{
        width: 48%;
        min-height: 50px;
        div{
            display: flex;
        }
        .detailTitle{
            font-weight: bold;
            display: inline-block;
            max-width: 120px;
            min-width: 60px;
        }
    }
}
</style>
